package com.example.forumsystem.demos.web.interceptor;

import com.example.forumsystem.demos.web.common.Constans;
import com.example.forumsystem.demos.web.exception.ApplicationException;
import com.example.forumsystem.demos.web.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${forumSystem.login.url}")
    private String defaultURL;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constans.USER_SESSION) != null){
            return true; //拥护是登录状态
        }
        //校验URL是否正确
        if (!defaultURL.startsWith("/")){
            defaultURL = "/" + defaultURL;
        }
        response.sendRedirect(defaultURL); //跳转页面
        log.warn("用户是未登录状态，被拦截了, url是：" + request.getRequestURI());
        return false;
    }
}
